package cn.edu.thu.laud.lasql.function.iface;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.UUID;

import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.UUIDGen;


import com.google.common.base.Charsets;

public class LaSQLFunctionUtil {

	public static ByteBuffer decompose(String value,boolean isUTF8)
	{
		if(isUTF8)
			return ByteBufferUtil.bytes(value, Charsets.UTF_8);
		else
			return ByteBufferUtil.bytes(value, Charsets.US_ASCII);
	}
	public static ByteBuffer decompose(Boolean value)
	{
		return (value==null) ? ByteBufferUtil.EMPTY_BYTE_BUFFER
				: value ? ByteBuffer.wrap(new byte[]{1})  // true
						: ByteBuffer.wrap(new byte[]{0}); // false
	}
	public static ByteBuffer decompose(Date value)
	{
		return (value==null) ? ByteBufferUtil.EMPTY_BYTE_BUFFER
				: ByteBufferUtil.bytes(value.getTime());
	}
	/**
	 * The bytes of the ByteBuffer are made up of 4 bytes of int containing the scale
	 * followed by the n bytes it takes to store a BigInteger.
	 */
	public static ByteBuffer decompose(BigDecimal value)
	{
		if (value == null) return ByteBufferUtil.EMPTY_BYTE_BUFFER;

		BigInteger bi = value.unscaledValue();
		Integer scale = value.scale();
		byte[] bibytes = bi.toByteArray();
		byte[] sbytes = ByteBufferUtil.bytes(scale).array();
		byte[] bytes = new byte[bi.toByteArray().length+4];

		for (int i = 0 ; i < 4 ; i++) bytes[i] = sbytes[i];
		for (int i = 4 ; i < bibytes.length+4 ; i++) bytes[i] = bibytes[i-4];

		return ByteBuffer.wrap(bytes);
	}
	public static ByteBuffer decompose(Double value)
	{
		return (value==null) ? ByteBufferUtil.EMPTY_BYTE_BUFFER : ByteBufferUtil.bytes(value);
	}
	public static ByteBuffer decompose(Float value)
	{
		return (value==null) ? ByteBufferUtil.EMPTY_BYTE_BUFFER : ByteBufferUtil.bytes(value);
	}
	public static ByteBuffer decompose(Integer value)
	{
		return ByteBufferUtil.bytes(value);
	}
	public static ByteBuffer decompose(UUID value)
	{
		return ByteBuffer.wrap(UUIDGen.decompose(value));
	}
	public static ByteBuffer decompose(Long value)
	{
		return ByteBufferUtil.bytes(value);
	}


}
